// pages/profile/profile.js - 严格按照test示例设计规范
const { api } = require('../../utils/api');

Page({
  data: {
    userInfo: {
      avatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f393f5c29478a7b382748e71c1d68ebb.png',
      name: '健身爱好者',
      userName: '',
      email: '',
      phonenumber: '',
      sex: '0',
      days: 128,
      trainings: 86,
      plans: 12,
      calories: '5.2k'
    },
    weeklyStats: {
      trainings: 5,
      increase: 2
    },
    monthlyStats: {
      duration: 4.5,
      increase: 1.2
    },
    loading: false
  },

  onLoad() {
    console.log('个人中心页面加载完成');
    this.loadUserProfile();
    this.initChart();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadUserProfile();
  },

  // 加载用户个人资料
  loadUserProfile() {
    this.setData({ loading: true });
    
    api.user.getProfile()
      .then(res => {
        console.log('获取个人资料成功', res);
        if (res.code === 200 && res.data) {
          const userData = res.data;
          this.setData({
            userInfo: {
              ...this.data.userInfo,
              name: userData.nickName || '健身爱好者',
              userName: userData.userName || '',
              email: userData.email || '',
              phonenumber: userData.phonenumber || '',
              sex: userData.sex || '0',
              avatar: userData.avatar || this.data.userInfo.avatar
            },
            loading: false
          });
          
          // 同步更新本地存储
          wx.setStorageSync('userInfo', {
            ...userData,
            nickName: userData.nickName
          });
        } else {
          this.setData({ loading: false });
          wx.showToast({
            title: res.msg || '获取用户信息失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取个人资料失败', err);
        this.setData({ loading: false });
        // 失败时从本地存储读取
        const localUserInfo = wx.getStorageSync('userInfo');
        if (localUserInfo) {
          this.setData({
            userInfo: {
              ...this.data.userInfo,
              name: localUserInfo.nickName || localUserInfo.name || '健身爱好者',
              avatar: localUserInfo.avatar || this.data.userInfo.avatar
            }
          });
        }
      });
  },

  // 加载用户数据
  loadUserData() {
    // 这里可以从服务器获取用户数据
    // 模拟数据已在data中定义
    console.log('加载用户数据');
  },

  // 跳转到个人资料
  goToProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit'
    });
  },

  // 跳转到我的成就
  goToAchievements() {
    wx.navigateTo({
      url: '/pages/profile/achievements'
    });
  },

  // 跳转到设置
  goToSettings() {
    wx.navigateTo({
      url: '/pages/profile/settings'
    });
  },

  // 跳转到帮助与反馈
  goToHelp() {
    wx.navigateTo({
      url: '/pages/profile/help'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除用户数据
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('token');
          
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/login/login'
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 更新用户信息
  updateUserInfo(userInfo) {
    this.setData({
      userInfo: {
        ...this.data.userInfo,
        ...userInfo
      }
    });
  },

  // 更新统计数据
  updateStats(stats) {
    this.setData({
      weeklyStats: {
        ...this.data.weeklyStats,
        ...stats.weekly
      },
      monthlyStats: {
        ...this.data.monthlyStats,
        ...stats.monthly
      }
    });
  },

  // 初始化图表
  initChart() {
    const ctx = wx.createCanvasContext('trainingChart', this);
    const data = [2, 1, 3, 1, 2, 0, 0]; // 周一到周日的训练次数
    const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    const maxValue = Math.max(...data);
    
    // 设置画布尺寸
    const canvasWidth = 300;
    const canvasHeight = 200;
    const padding = 40;
    const chartWidth = canvasWidth - padding * 2;
    const chartHeight = canvasHeight - padding * 2;
    
    // 绘制背景
    ctx.setFillStyle('#f9fafb');
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    
    // 绘制坐标轴
    ctx.setStrokeStyle('#e5e7eb');
    ctx.setLineWidth(1);
    
    // X轴
    ctx.beginPath();
    ctx.moveTo(padding, canvasHeight - padding);
    ctx.lineTo(canvasWidth - padding, canvasHeight - padding);
    ctx.stroke();
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, canvasHeight - padding);
    ctx.stroke();
    
    // 绘制网格线
    ctx.setStrokeStyle('#f3f4f6');
    ctx.setLineWidth(0.5);
    for (let i = 1; i <= 4; i++) {
      const y = padding + (chartHeight / 4) * i;
      ctx.beginPath();
      ctx.moveTo(padding, y);
      ctx.lineTo(canvasWidth - padding, y);
      ctx.stroke();
    }
    
    // 绘制柱状图
    const barWidth = chartWidth / data.length * 0.6;
    const barSpacing = chartWidth / data.length;
    
    data.forEach((value, index) => {
      const barHeight = (value / maxValue) * chartHeight;
      const x = padding + barSpacing * index + (barSpacing - barWidth) / 2;
      const y = canvasHeight - padding - barHeight;
      
      // 绘制柱子
      ctx.setFillStyle('#10b981');
      ctx.fillRect(x, y, barWidth, barHeight);
      
      // 绘制数值标签
      ctx.setFillStyle('#1f2937');
      ctx.setFontSize(12);
      ctx.setTextAlign('center');
      ctx.fillText(value.toString(), x + barWidth / 2, y - 5);
      
      // 绘制日期标签
      ctx.setFillStyle('#6b7280');
      ctx.setFontSize(10);
      ctx.fillText(labels[index], x + barWidth / 2, canvasHeight - padding + 15);
    });
    
    ctx.draw();
  }
});
